/**
 * Copyright (C) 2024-2030 Super BilGen & 超亿时代信息技术股份有限公司.All Rights Reserved.
 */
package cn.com.yang.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSON;

import cn.com.yang.utils.WebUtil;

/**
 * @Model cn.com.yang.controller.TestThreadLocalController
 * @Desc  TODO
 * @author yangyijin
 * @since 2024年11月29日-下午4:30:53
 */
@RestController
@RequestMapping("/api")
public class TestThreadLocalController {
	private Logger logger =LoggerFactory.getLogger(getClass());
	
	private static ThreadLocal<Map<String, Object>> cache = new ThreadLocal<Map<String, Object>>() {
		@Override
        protected final Map<String, Object> initialValue() {
            return new HashMap<String, Object>();
        }
    };
	
	@PostMapping("/threadlocal/set")
	public String set(HttpServletRequest request,HttpServletResponse response) {
		String req = WebUtil.postReqBodyToStr(request);
		logger.info("获取前端上送报文:{}",req);
		Map<String,Object> map = JSON.parseObject(req, Map.class);
		for(String key:map.keySet()) {
			cache.get().put(key, map.get(key));
		}
		cache.get().put("str", "123");
		return (String)cache.get().toString();
	}
	
	/**
	 * 有问题
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/threadlocal/get")
	public String get(HttpServletRequest request,HttpServletResponse response) {
		String req = WebUtil.postReqBodyToStr(request);
		logger.info("获取前端上送报文:{}",req);
		Map<String,Object> map = JSON.parseObject(req, Map.class);
		logger.info("cache.get():{}",cache.get().toString());
		return "key:" +map.get("key") + ">> val:"+cache.get().get("str");
	}
}
